package com.qs.services;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qs.dao.FeedDAO;
import com.qs.entities.Channel;
import com.qs.entities.Feed;
import com.qs.entities.User;
import com.qs.exceptions.ServiceException;

public class FeedService {
	
	protected final Logger log = LoggerFactory.getLogger(FeedService.class);
	
	private FeedDAO feedDao;
	
	public List<Feed> getFeeds(int offset,int limit,String channelId) throws ServiceException {
		log.debug("getting feeds. offset:"+offset+", limit:"+limit);
		try{
			if(NumberUtils.isNumber(channelId)){
				return feedDao.findAllByLimit(offset, limit, new Channel(Integer.parseInt(channelId)));
			}
			
			return feedDao.findAllByLimit(offset, limit);
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(),exc);
		}	
	}
	
	public Feed createFeed(String userId,String channelId,String text) throws ServiceException{
		log.debug("creating feed. userId:"+userId+", channelId:"+channelId+", text:"+text );
		try{
			Feed transientInstance = new Feed();
			
			transientInstance.feedId 	= UUID.randomUUID().toString();
			transientInstance.user		= new User(userId);
			transientInstance.channel	= new Channel(Integer.parseInt(channelId));
			transientInstance.text		= text;
			
			feedDao.save(transientInstance);
			
			return transientInstance;
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(),exc);
		}
	}

	public FeedDAO getFeedDao() {
		return feedDao;
	}

	public void setFeedDao(FeedDAO feedDao) {
		this.feedDao = feedDao;
	}

	

	
	
}
